import { import_platformuser } from "@/services/platformuser";
import { LoadingOutlined } from "@ant-design/icons";
import { ActionType } from "@ant-design/pro-components";
import { Button, Divider, Modal, Spin, Upload, message } from "antd";
import ExportJsonExcel from 'js-export-excel';
import { useState } from "react";
import { read, utils } from 'xlsx';
import moment from "moment";

interface Iprops {
    isShowImportDoctorModal: (show: boolean) => void;
    importDoctor: boolean;
    actionRef: React.MutableRefObject<ActionType | undefined>;
}

const ImportDoctor=(props:Iprops)=>{
    const {isShowImportDoctorModal,importDoctor,actionRef}=props
    // 存储上传成功状态
    const [flag, setFlag] = useState(false)
    // 存储上传成功条数
    const [success_count, setSuccess_count] = useState(0)
    // 存储上传失败条数
    const [failed_count, setFailed_count] = useState(0)
    // 存储上传失败数据
    const [failed_data, setFailed_data] = useState([])
    // 控制loading状态
    const [isShowLoading, setIsShowLoading] = useState(false)


        // 下载员工信息模板
        const downloadDoctor = (tableName: string = '员工信息模板') => {
            const XLSX = require("xlsx");
            const XLSXStyle = require("xlsx-style");
            // 创建工作簿
            const workbook = XLSX.utils.book_new();
            // 自定义表头
            let headers = {
                phone: '*手机号',
                username: '*员工姓名',
                sex: '性别',
                birth: '出生日期（示例：2024-05-06）',
            }
            const worksheet = XLSX.utils.json_to_sheet([headers], {
                header: ['phone', 'username', 'sex', 'birth'],
                skipHeader: true
            });
            // 设置列宽
            worksheet['!cols'] = [{ wch: 12 }, { wch: 15 }, { wch: 10 }, { wch: 25 }]
            XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet1")
            let arr=[{row:'A1',text:"*手机号"},{row:'B1',text:'*员工姓名'}]
            let arr2=[{row:'C1',text:"性别"},{row:'D1',text:'出生日期（示例：2024-05-06）'}]
            // 设置某个单元格样式
            arr.map((item:any)=>{
                 worksheet[item.row] = {
                t: 's',
                v: item.text,
                s: {
                    font: {
                        sz:9,
                        color: { rgb: 'ff0000' }
                    },
                    alignment:{
                        wrapText:true,
                        indent:1,
                        horizontal:'centerContinuous',
                        vertical:'center'
                    }
                }
            }
            })
            arr2.map((item:any)=>{
                worksheet[item.row] = {
               t: 's',
               v: item.text,
               s: {
                   font: {
                       sz:9,
                   },
                   alignment:{
                       wrapText:true,
                       indent:1,
                       horizontal:'centerContinuous',
                       vertical:'center'
                   }
               }
           }
           })
           
            // 使用xlsx-style写入文件方式，使得自定义样式生效
            const tempDown = new Blob([
                s2ab(
                    XLSXStyle.write(workbook, {
                        bookType: 'xlsx',
                        bookSST: true,
                        type: 'binary',
                        cellStyles: true
                    })
                )
            ])
            // 导出excel文件
            downExcel(tempDown, tableName + '.xlsx')
    
        }
        // 自定义下载文件方法
        const downExcel = (obj: any, fileName: string) => {
            const a_node = document.createElement('a');
            a_node.download = fileName;
            if ('msSaveOrOpenBlob' in navigator) {
                window.navigator.msSaveOrOpenBlob(obj, fileName);
            } else {
                a_node.href = URL.createObjectURL(obj)
            }
            a_node.click();
            setTimeout(() => {
                URL.revokeObjectURL(obj)
            }, 2000)
        }
        // 文件流转换
        const s2ab:any = (s: any) => {
            if (typeof ArrayBuffer !== 'undefined') {
                const buf = new ArrayBuffer(s.length);
                const view = new Uint8Array(buf);
                for (let i = 0; i != s.length; i++) {
                    view[i] = s.charCodeAt(i) & 0xff;
                }
                return buf;
            } else {
                const buf = new Array(s.length);
                for (let i = 0; i != s.length; i++) {
                    buf[i] = s.charCodeAt(i) & 0xff;
                }
                return buf;
            }
        }

    // 解析上传的excel文件 读取数据
    const analyseExcelToJson = (file: any) => {
        return new Promise((resolve, reject) => {
            // console.log(file);
            if (file.originFileObj instanceof File) {
                const reader = new FileReader();
                reader.onloadend = (progressEvent: any) => {
                    const data = new Uint8Array(progressEvent.target.result);
                    const options: any = { type: 'array' };
                    const workbook = read(data, options);
                    const sheetName: any = workbook.SheetNames;
                    const sheet = workbook.Sheets[sheetName[0]];
                    const jsonData = utils.sheet_to_json(sheet, { header: 1, defval: '', blankrows: false })
                    resolve(jsonData);
                };
                reader.readAsArrayBuffer(file.originFileObj);
            } else {
                reject(new Error('入参不是 File 类型'));
            }
        });
    };
     //批量导入
     const uploadprops = {
        name: 'file',
        accept: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        showUploadList: false,
        onChange(info: any) {
            if (info.file.status !== 'uploading') {
                setIsShowLoading(true)
                setFlag(false)
                analyseExcelToJson(info.file).then(async (result: any) => {
                    // console.log('表格数据', result.slice(1))
                    let res: any = [];
                    const newArr = result.slice(1)
                    const newPhoneListLength = new Set(newArr.map((item: any) => item[0])).size;
                    // console.log('newPhoneListLength', newPhoneListLength);
                    // console.log('newIdCardListLength', newIdCardListLength);
                    //判断 result 中 必填字段是否为空
                    if (newArr.some((item: any) => item[0].toString().trim() === '' || item[1].toString().trim() === '')) {
                        message.error('上传失败，表格内有必填项为空！')
                        setIsShowLoading(false)
                        return;
                    }
                    //判断 result 中 是否有重复手机号
                    //判断 result 中 是否有重复身份证号
                    if (newArr.length != newPhoneListLength) {
                        message.error('上传失败，表格内数据有手机号重复！')
                        setIsShowLoading(false);
                        return;
                    }
                    newArr.map((item: any) => res.push({ 'phone': item[0], 'name': item[1], 'sex': item[2], 'birth': item[3].toString().trim()}));
                    // console.log('res',res);
                    let params: any = await import_platformuser({ platformuser_list: JSON.stringify(res,null) });
                    console.log('params',params);
                    if (params.code == 200) {
                        message.success('上传成功！')
                        setIsShowLoading(false)
                        // 刷新外侧列表
                        actionRef.current?.reload()
                        setFlag(true)
                        setSuccess_count(params.data.success_count)
                        setFailed_count(params.data.failed_count)
                        setFailed_data(params.data.failed)
                    } else {
                        message.error(params.msg)
                        setIsShowLoading(false)
                    }
                });
            }
        }
    };
     // 下载上传失败数据
     const downloadFailedData = (tableName: string = '上传失败数据') => {
        // 存储表格数据
        let tableData: any = [];
        // 添加标题行
        let title = ['手机号', '员工姓名', '性别', '出生日期（示例：2024-05-06）','失败原因'];
        failed_data.map((item: { phone: string; name: string; sex: number; birth: string; failed_reason: string }) => {
            let objRow = {
                '手机号': item.phone,
                '员工姓名': item.name,
                '性别': item.sex==1?'男':item.sex==2?'女':'未知',
                '出生日期（示例：2024-05-06）': item.birth,
                '失败原因':item.failed_reason
            }
            tableData.push(objRow)
        })

        var option = {
            fileName: tableName,
            datas: [
                {
                    sheetHeader: title,//表头数据
                    sheetData: tableData,//数据源
                    sheetName: 'sheet',
                    sheetFilter: title,
                    columnWidths: ['5', '5', '5', '12', '12']
                }
            ]
        };
        let toExcel = new ExportJsonExcel(option);
        toExcel.saveExcel();
    }
    return (
        <Modal
            title="导入员工"
            open={importDoctor}
            onCancel={() => isShowImportDoctorModal(false)}
            width={500}
            destroyOnClose={true}
            footer={null}
        >
            <Divider />
            <div style={{ cursor: 'pointer' }} onClick={() => downloadDoctor()}>1、下载<span style={{ color: '#1677FF' }}>《员工信息模板》</span>，批量导入员工信息</div>
            <div style={{ marginTop: '20px', display: 'flex', alignItems: 'center', }}>2、上传填写好的员工信息模板 <div style={{ margin: '0 10px 0 10px' }}><Upload {...uploadprops}>
                <Button>上传</Button>
            </Upload></div> {isShowLoading ? <Spin indicator={<LoadingOutlined style={{ fontSize: 24 }} spin />} /> : ''}</div>
            {flag ? <div style={{ marginTop: "20px", display: 'flex' }}>导入结果：成功导入{success_count}条数据，{failed_count}条失败 {failed_count > 0 ? <div style={{ color: '#1677FF', cursor: 'pointer', marginLeft: '20px' }} onClick={() => downloadFailedData()}>下载失败数据</div> : ""}</div> : ""}
        </Modal>
    )
}
export default ImportDoctor;